﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Nacos.V2;

namespace Service.Core.OpenFegin
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="httpContextAccessor"></param>
    /// <param name="serviceProvider"></param>
    /// <param name="logger"></param>
    public class ServiceDiscoveryHandler(IHttpContextAccessor httpContextAccessor, IServiceProvider serviceProvider, ILogger<ServiceDiscoveryHandler> logger) : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // 1. 获取当前请求的目标 Host（占位符）
            var serviceName = request.RequestUri.Host;
            try
            {
                // ✅ 2. 创建作用域获取 Nacos 服务
                using var scope = serviceProvider.CreateScope();
                var serviceDiscovery = scope.ServiceProvider.GetRequiredService<IServiceDiscoveryService>();
                // ✅ 3. 从 Nacos 获取健康实例
                var instance = await serviceDiscovery.GetInstancesAsync(serviceName);

                logger.LogInformation("Routing {Original} to {Real}", request.RequestUri, instance);
                // ✅ 5. 替换请求地址
                request.RequestUri = instance;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed to resolve service instance for {ServiceName}", serviceName);
                throw;
            }

            // ✅ 6. 发送请求
            return await base.SendAsync(request, cancellationToken);


        }

    }


}
